package com.logistics.web;

import java.io.File;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.logistics.Shop;
import com.logistics.ShopQueryParam;
import com.logistics.admin.AdminGenericBaseAction;
import com.logistics.service.ShopService;

@Component("shopAdminAction")
@Scope("prototype")
public class ShopAdminAction extends AdminGenericBaseAction<Shop, ShopService> {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private ShopService service;
	
	@Autowired
	public void setService(ShopService service) {
		this.service = service;
	}

	@Override
	public ShopService getService() {
		return service;
	}
	
	private Shop shop;

	public Shop getShop() {
		return shop;
	}

	public void setShop(Shop shop) {
		this.shop = shop;
	}
	
	private List<Shop> shops;
	
	public List<Shop> getShops() {
		return shops;
	}

	public void setShops(List<Shop> shops) {
		this.shops = shops;
	}
	
	private ShopQueryParam param;

	public ShopQueryParam getParam() {
		return param;
	}

	public void setParam(ShopQueryParam param) {
		this.param = param;
	}

	private File thumbnail;

	public File getThumbnail() {
		return thumbnail;
	}

	public void setThumbnail(File thumbnail) {
		this.thumbnail = thumbnail;
	}
	
	private String thumbnailFileName;

	public String getThumbnailFileName() {
		return thumbnailFileName;
	}

	public void setThumbnailFileName(String thumbnailFileName) {
		this.thumbnailFileName = thumbnailFileName;
	}
	
	private String oldThumbnail;

	public String getOldThumbnail() {
		return oldThumbnail;
	}

	public void setOldThumbnail(String oldThumbnail) {
		this.oldThumbnail = oldThumbnail;
	}

	@Override
	protected Shop initEntityForAdd() {
		if (thumbnail.exists()) {
			shop.setThumbnail(saveImageFile(thumbnail, thumbnailFileName, getImageUploadFolder(Shop.SHOP_FOLDER)));
			deleteFile(oldThumbnail, getImageUploadFolder(Shop.SHOP_FOLDER));
		} else {
			shop.setThumbnail(oldThumbnail);
		}
		return shop;
	}
	
	public String list() {
		if (param == null) {
			param = new ShopQueryParam();
		}
		
		param.setPaging(getPaging());
		
		shops = service.query(param);
		return LIST;
	}
	
	@Override
	protected void initEditForm() {
		shop = service.getById(getId());
		super.initEditForm();
	}
	
	public String getShopImage(String name) {
		if (StringUtils.isEmpty(name)) {
			return null;
		}
		
		return getImageURl(Shop.SHOP_FOLDER, name);
	}
	
}
